package com.yyq.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.yyq.io.Resources;
import com.yyq.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Author yuanyueqiang
 * @Date 2021-11-27 21:24
 */
public class XmlConfigureBuilder {

    private Configuration configuration;

    public XmlConfigureBuilder(){
        this.configuration = new Configuration();
    }

    /**
     * 解析sqlMapConfig.xml
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        //<Configuration>
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            properties.put(element.attributeValue("name"),element.attributeValue("value"));
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        String driverClassName = properties.getProperty("driverClassName");
        String jdbcUrl = properties.getProperty("jdbcUrl");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        comboPooledDataSource.setDriverClass(driverClassName);
        comboPooledDataSource.setJdbcUrl(jdbcUrl);
        comboPooledDataSource.setUser(username);
        comboPooledDataSource.setPassword(password);
        configuration.setDataSource(comboPooledDataSource);
        //mapper.xml解析: 拿到路径--字节输入流--dom4j进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream in = Resources.getResourcesAsStream(mapperPath);
            XmlMapperBuilder builder = new XmlMapperBuilder(configuration);
            builder.parse(in);
        }
        return configuration;
    }

}
